package com.backend.demo1.controller;

import com.backend.demo1.config.ApiResponse;
import com.backend.demo1.models.Match;
import com.backend.demo1.services.MatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/matchs")
public class MatchController {

    @Autowired
    private MatchService matchService;

    // 创建比赛信息
    @PostMapping
    public ResponseEntity<ApiResponse<Match>> createMatch(@RequestBody Match match) {
        try {
            Match createdMatch = matchService.createMatch(match);
            return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(createdMatch));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.error(400, e.getMessage()));
        }
    }

    // 获取比赛列表
    @GetMapping
    public ResponseEntity<ApiResponse<List<Match>>> getMatchesList() {
        try {
            List<Match> matches = matchService.getMatchesList();
            return ResponseEntity.ok(ApiResponse.success(matches));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(500, e.getMessage()));
        }
    }

    // 根据 ID 获取比赛信息
    @GetMapping("/{matchId}")
    public ResponseEntity<ApiResponse<Match>> getMatchById(@PathVariable Long matchId) {
        try {
            Match match = matchService.getMatchById(matchId);
            return ResponseEntity.ok(ApiResponse.success(match));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.error(404, e.getMessage()));
        }
    }

    // 更新比赛信息
    @PutMapping("/{matchId}")
    public ResponseEntity<ApiResponse<String>> updateMatch(@PathVariable Long matchId, @RequestBody Match inputMatch) {
        try {
            matchService.updateMatch(matchId, inputMatch);
            return ResponseEntity.ok(ApiResponse.success("比赛信息更新成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiResponse.error(500, e.getMessage()));
        }
    }

    // 删除比赛信息
    @DeleteMapping("/{matchId}")
    public ResponseEntity<ApiResponse<String>> deleteMatch(@PathVariable Long matchId) {
        try {
            matchService.deleteMatch(matchId);
            return ResponseEntity.ok(ApiResponse.success("比赛信息删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiResponse.error(500, e.getMessage()));
        }
    }
}